<template>
  <div class="lilith-chat-textarea">
    <el-input :model-value="text" type="textarea" :placeholder="placeholder" @input="$emit('update:text', $event)" :rows="rows"></el-input>
    <div class="textarea-handle" v-if="robot">
      <el-button class="FormBtn" @click="showRobot" round><el-icon class="icon"><Avatar /></el-icon><span class="txt">AI优化</span></el-button>
    </div>

    <el-drawer custom-class="chat-drawer" v-model="showRobotDialog" title="AI助手" :destroy-on-close="false" :style="{minWidth: '432px'}" :z-index="2100">
      <div class="lilith-chat">

        <div class="chat-context" ref="chatContext">
          <div v-for="(v, i) in chatList" :key="'chattext' + i">
            <div class="chattext-item right">
              <div class="chattext">
                {{ v.question || '' }}
              </div>
            </div>

            <div class="chattext-item left" v-if="v.answer">
              <div class="chat-avatar">
                <div class="lilith-info">
                  <img src="http://lilithai.msyc.cc/pro-api/data/admin-upload/24012413444069823.jpg" /><span>莉莉丝</span>
                </div>
              </div>
              <div class="chattext" v-html="replaceHtml(v.answer || '')">
              </div>
              <div class="chat-handle">
                <el-button @click="adoptText" :data-text="v.answer" size="small" ><el-icon class="icon"><CircleCheckFilled /></el-icon><span class="txt">采用</span></el-button>
              </div>
            </div>
          </div>

          <div class="loading-chat" v-if="loading">
            <div></div>
            <div></div>
            <div></div>
          </div>
        </div>

        <div class="chat-input-wrap">
          <el-button class="btn-clear" @click="clear"><el-icon class="icon"><DocumentAdd /></el-icon></el-button>
          <el-input class="textarea" v-model="chatTxt" type="textarea" placeholder="请输入您的问题并展开讨论" rows="1" />
          <el-button class="btn-send" @click="sendText"><el-icon class="icon"><Avatar /></el-icon><span class="txt">提问</span></el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
 
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
.lilith-chat-textarea .chat-input-wrap { 
  .el-textarea__inner{ border-radius: 16px;}
}
.chattext img{height:16px !important; width: auto !important; }
.chattext > div{display: block !important; vertical-align: baseline;}
</style>
<style lang="scss" scoped>
.lilith-chat-textarea { width: 100%; }
.textarea-handle { display: flex; align-items: center;justify-content: flex-end; margin-top: 8px; }
.lilith-chat { position: relative; height: 100%; display: flex; flex-direction: column; justify-content: space-between; }

.chat-avatar {
  display: flex; align-items: center; justify-content: space-between;margin-right: 24px;
  .lilith-info { display: flex; align-items: center;}
  img { width: 22px; height: 22px; border-radius: 999px;margin-right: 4px; }
}

.chat-context { padding-right: 12px; overflow-y: auto; }

.chattext-item {
  text-align: left; margin-bottom: 12px;
  .chattext { display: inline-block; padding: 8px 12px;line-height: 1.5; text-align: left;border-radius: 4px;background: #f6f6f6; margin-right: 24px;}
  .chat-handle { text-align: right; margin-right: 24px; }
  &.right { 
    text-align: right; 
    .chat-avatar { justify-content: flex-end; margin-right: 0; }
    .chattext { background: #d4e9ff; margin-right: 0;margin-left: 24px; }
  }
}

.chattext img{height:16px !important; width: auto !important; }
.chattext > div{display: block !important; vertical-align: top; line-height: 16px;}
.chat-input-wrap { 
  display: flex; padding: 12px 0; background: #ffffff; line-height: 16px;
  .btn-clear{margin-right: 8px;height: 100%; width: 32px; height: 32px; border-radius: 16px; background: #21213c; color: #fff; border:none; }
  .btn-send { height: 100%; margin-left: 8px; border-radius: 16px; color: #fff; background: #21213c; border:none; }
}

.loading-chat {
  > div { 
    display: inline-block; width: 15px; height: 15px; border-radius: 100%; margin: 2px; background-color: #ccc; -webkit-animation-fill-mode: both; animation-fill-mode: both;
    &:nth-child(1) {
      -webkit-animation: ball-scale 0.75s 0.12s infinite cubic-bezier(.2, .68, .18, 1.08);
      animation: ball-scale 0.75s 0.12s infinite cubic-bezier(.2, .68, .18, 1.08);
    }
    &:nth-child(2) {
      -webkit-animation: ball-scale 0.75s 0.24s infinite cubic-bezier(.2, .68, .18, 1.08);
      animation: ball-scale 0.75s 0.24s infinite cubic-bezier(.2, .68, .18, 1.08);
    }
    &:nth-child(3) {
      -webkit-animation: ball-scale 0.75s 0.36s infinite cubic-bezier(.2, .68, .18, 1.08);
      animation: ball-scale 0.75s 0.36s infinite cubic-bezier(.2, .68, .18, 1.08);
    }
  }
}
@keyframes ball-scale {
  0% {
    -webkit-transform: scale(1);
    transform: scale(1);
  }
  50% {
    -webkit-transform: scale(0.5);
    transform: scale(0.5);
    opacity: 0.7;
  }
  100% {
    -webkit-transform: scale(1);
    transform: scale(1);
    opacity: 1;
  }
}
</style>
<script>
import WebRequest from '../../unit/request.js'
export default {
  name: 'LilithChat',
  components:{  },
  props: {
    rows: 6,
    text: '',
    // 占位内容
    placeholder: {
      type: String,
      default: ''
    },
    // 是否显示机器人选项
    robot: {
      type: Boolean,
      default: false
    },
  },
  emits: ['update:text'],
  data () {
    return {
      robotId: 79,//79:AI生图提示词助手, 52:莉莉丝	,
      testToken: 'nfaxNJJF5oLZ-gPCn3d0J3oucZ636SGY_1701079527',
      chatTxt: '',              // 聊天文本
      showRobotDialog: false,   // 是否显示弹窗

      liliRobot: null,          // 机器人
      chatId: null,             // 对话ID
      chatList: [],             // 对话列表

      loading: false,           // 是否加载中
      isFirstOpen: true,
    }
  },
  mounted() {
    // 设置测试token
    WebRequest.Lili.token = this.testToken
  },
  methods: {

    clear(){
      let res = WebRequest.Lili.Clear({ chat_id: this.chatId })
      console.log(res);
      this.showRobot();
    },
    autoSend(){
      if(this.isFirstOpen && this.text && this.text != ''){
        console.log("is first open")
        this.isFirstOpen = false
        this.clear();
        let sendTxt = this.text;
        this.sendText(null,sendTxt);
      }
    },
    // 显示AI助手
    showRobot() {
      if (!this.liliRobot) {
        setTimeout(async () => {
          try {
            // 获取机器人
            this.liliRobot = await WebRequest.Lili.getView({ id: this.robotId })
            // 获取对话id和对话列表
            let peopleData = await WebRequest.Lili.getChatPeople({ chat_id: 0, model_id: this.robotId })
            this.chatId = peopleData.data.data.chat_id
            this.chatList = peopleData.data.data.data || []
            this.scrollBottom()
            this.autoSend()
          } catch (error) {
            console.log(error)
          }
        }, 100)
      }else{
        this.autoSend()
      }
      this.showRobotDialog = true
    },

    // 发送文本
    async sendText (e,txt) {
      if (this.loading || ((!txt || txt=='') && (!this.chatTxt || this.chatTxt == ''))) {
        return
      }
      try {
        let text = this.chatTxt
        if(txt){
          text = txt
        }
        // 创建问题数据
        let qItem = {
          question: text,
          answer: null,
        }
        this.loading = true
        this.chatList.push(qItem)
        this.scrollBottom(100, () => {
          //this.chatTxt = this.text
          this.chatTxt = ""
        })
        // 提交问题
        let res = await WebRequest.Lili.postChat({
          chat_id: this.chatId,
          prompt: text,
          model_id: this.robotId,
          type: 1,
          use_model: 3
        })
        if (res.status == 200) {
          let session_id = res.data.data.session_id
          // 获取问题答案
          let answer = await WebRequest.Lili.getAnswer({ session_id })
          // 添加答案
          if (answer.data) {
            this.chatList[this.chatList.length - 1].answer = answer.data
            this.scrollBottom()
            this.loading = false
          }
        }
      } catch (error) {
        this.loading = false
        console.log(error)
      }
    },

    replaceHtml(text) {
      return text.replace(/\n/g, '</br>')
    },

    // 采用文本
    adoptText(e) {
      let text = e.currentTarget.dataset.text || ''
      this.$emit('update:text', text)
      this.showRobotDialog = false
    },

    // 滚动到底部
    scrollBottom(time = 100, callBack) {
      setTimeout(() => {
        let $cct = this.$refs['chatContext']
        let height = $cct.scrollHeight
        $cct.scrollTop = height
        callBack && callBack()
      }, time)
    },
  }
}
</script>

